//
//  MainTabBarController.swift
//  MyBlog
//
//  Created by lvtienan on 15/7/28.
//  Copyright © 2015年 ltn. All rights reserved.
//

import UIKit

class MainTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // 在这里的时候tabbarzzVutton 还没有创建
        addChildViewController()
        
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 此时 tabBarButton 都已经创建
        setupComposedButton()
    }
    
    
    
    
    
    /**
    添加所有的子控制器
    */
    private func addChildViewController() {
        
        addChildViewController(HomeTableViewController(), title: "首页", imagename: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imagename: "tabbar_message_center")
        
        // 设置中间的按钮(预留位置)
        addChildViewController(UIViewController())
        addChildViewController(DiscoveryTableViewController(), title: "发现", imagename: "tabbar_discover")
        addChildViewController(DiscoveryTableViewController(), title: "我", imagename: "tabbar_profile")
        
    }
    
    /**
    添加子控制器
    - parameter vc       : 控制器对象
    - parameter title    : tabBar 的 w文本
    - parameter imagename: tabBar 的图片名称
    */
    private func addChildViewController(vc:UITableViewController, title:String, imagename:String) {
        

        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: imagename)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
        
        
    }
    
    /// MARk - 懒加载 Button 控件
    lazy private var composeButton: UIButton = {
        
        let button = UIButton()
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        self.tabBar.addSubview(button)
        
        button.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)

        return button
        
    }()

    /**
    设置按钮的位置
    */
    private func setupComposedButton() {
        
         let w = tabBar.bounds.width / CGFloat(viewControllers!.count)
        
        let rect = CGRect(x: 0, y: 0, width: w, height: tabBar.bounds.height)
        
        composeButton.frame = CGRectOffset(rect, 2 * w, 0)
    }
    
    
    /**
    按钮点击
    */
    func clickComposedButton() {
        print(__FUNCTION__)
    }
    
}









